// 教师控制器
package org.example.backend.controller;

import jakarta.validation.Valid;
import org.example.backend.dto.TeacherDto;
import org.example.backend.entity.Teacher;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.service.TeacherService;
import org.example.backend.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/teacher")
@CrossOrigin
@PreAuthorize("hasRole('TEACHER')")
public class TeacherController {

    private static final Logger logger = LoggerFactory.getLogger(TeacherController.class);

    private final TeacherService teacherService;
    private final UserService userService;

    public TeacherController(TeacherService teacherService, UserService userService) {
        this.teacherService = teacherService;
        this.userService = userService;
    }

    /**
     * 教师注册（完善个人信息）
     */
    @PostMapping("/register")
    public ResponseEntity<?> registerTeacher(@Valid @RequestBody TeacherDto teacherDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 创建教师信息
            Teacher teacher = teacherService.createTeacher(teacherDto, user.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "教师信息注册成功");
            response.put("teacher", teacher);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("教师注册失败", e);
            return ResponseEntity.badRequest().body("注册失败：" + e.getMessage());
        }
    }

    /**
     * 更新教师信息
     */
    @PutMapping("/profile")
    public ResponseEntity<?> updateTeacher(@Valid @RequestBody TeacherDto teacherDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取教师信息
            Teacher existingTeacher = teacherService.getTeacherByUserId(user.getId());

            // 更新教师信息
            Teacher teacher = teacherService.updateTeacher(existingTeacher.getId(), teacherDto);

            Map<String, Object> response = new HashMap<>();
            response.put("message", "教师信息更新成功");
            response.put("teacher", teacher);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新教师信息失败", e);
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }

    /**
     * 获取教师个人信息
     */
    @GetMapping("/profile")
    public ResponseEntity<?> getTeacherProfile() {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取教师信息
            Teacher teacher = teacherService.getTeacherByUserId(user.getId());

            return ResponseEntity.ok(teacher);
        } catch (Exception e) {
            logger.error("获取教师信息失败", e);
            return ResponseEntity.badRequest().body("获取信息失败：" + e.getMessage());
        }
    }
}
